﻿using FireChat.Share.Logger.Printer;

namespace FireChat.Share.Logger;


/// <summary>
/// 日志记录器
/// </summary>
public static class LoggerScaffold
{
    /// <summary>
    /// 日志缓冲区
    /// </summary>
    private static readonly LogBuffer _buffer = new(1024);



    /// <summary>
    /// Logger 初始化操作
    /// </summary>
    static LoggerScaffold()
    {
        static async void BufferReader()
        {
            while(true)
            {
                if (_buffer.Pop() is not ILogPrinter logPrint)
                {
                    await Task.Delay(10);
                    continue;
                }

                logPrint.Print();
            }
        }

        //异步执行日志打印
        Task.Run(BufferReader);
    }



    /// <summary>
    /// 记录一个日志
    /// </summary>
    public static void Push(this ILogPrinter logPrinter)
    {
        _buffer.Push(logPrinter);
    }

    /// <summary>
    /// 记录日志到控制台
    /// </summary>
    /// <param name="level">日志等级</param>
    public static void LogToConsole(this string message, LogLevel level = LogLevel.Info)
    {
        if(string.IsNullOrWhiteSpace(message))
        {
            return;
        }

        Push(new ConsoleLogPrinter()
        {
            Level = level,
            Message = message,
            LogTime = DateTime.Now
        });
    }

    /// <summary>
    /// 记录日志到控制台
    /// </summary>
    /// <param name="level">日志等级</param>
    public static void LogToConsole(this Exception ex, LogLevel level = LogLevel.Error)
    {
        Push(new ConsoleLogPrinter()
        {
            Level = level,
            Message = ex.Message,
            LogTime = DateTime.Now,
            Exception = ex
        });
    }
}
